package com.zige.zige.task;

import android.app.Activity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.zige.zige.utils.ToastUtils;

import java.util.Map;

/**
 * 处理get请求
 * Created by song on 2015/4/7.
 */
public abstract class GetRequestTask extends ITask {


    RequestQueue requestQueue;

    protected GetRequestTask(Map<String, String> params, Activity context, String url) {
        this.params = params;
        this.context = context;
        this.url = url;
    }


    @Override
    public void handleTask() {
        requestQueue = Volley.newRequestQueue(context);
        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                handleResponse(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        ToastUtils.showToast(context, "网络连接失败");

//                        context.startActivity(new Intent(context, NetErrorActivity.class));
                        handleErrorResponse(error);
                    }
                });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }

    protected abstract void handleErrorResponse(VolleyError error);

    protected abstract void handleResponse(String response);

    public void stop() {
        requestQueue.cancelAll(context);
    }
}
